package com.springbatch.springbatch.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.listener.StepExecutionListenerSupport;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.util.Assert;

import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


public class StepBeforeAfterListener extends StepExecutionListenerSupport  {
    private static final Logger log = LoggerFactory.getLogger(StepBeforeAfterListener.class);

    private Resource[] resources;
    private  String backupFolder;
    private  String sqlProcess;
    protected NamedParameterJdbcOperations namedParameterJdbcTemplate;


    @Override
    public void beforeStep(StepExecution stepExecution) {
        super.beforeStep(stepExecution);
        //读取初始化文件需要truncate数据库， 如：CCBIns_Inf_INIT_0001.dat
        try {
            if(resources != null)
                for(int i = 0; i < resources.length; i++) {
                    File sourceFile = resources[i].getFile();
                    String fileName = sourceFile.getName();
                    if(fileName.contains("_INIT_")) {
                        log.info("开始初始化表，进行trancate操作， 执行sqlProcess... ...");
                        log.info("SQL语句：" + sqlProcess);
                        if (namedParameterJdbcTemplate != null)
                            namedParameterJdbcTemplate.update(sqlProcess, new HashMap<>());
                    }
                }
            } catch (IOException e) {
            log.error(e.getMessage());
         }
    }

    @Override
        public ExitStatus afterStep(StepExecution stepExecution) {
            log.info("This step:" + stepExecution.getStepName()
                    + " is done with id:"
                    + stepExecution.getJobExecutionId());
            if(stepExecution.getStatus() == BatchStatus.COMPLETED) {
                    ProcessFileResources(resources);
            }
            return stepExecution.getExitStatus();
        }

    private void ProcessFileResources(Resource[] resources)   {
        try {
            if(resources != null)
                for(int i = 0; i < resources.length; i++)
                {
                    File sourceFile  = resources[i].getFile();
                    File dir = new  File(sourceFile.getParent());
                    String  parentFolder = dir.getName();
                    File targetFile=new File(backupFolder
                            + File.separator + parentFolder
                            + File.separator + sourceFile.getName());
                    log.info("Move file  from : " + sourceFile.getPath() + " to " + targetFile.getPath());

                    //删除目标文件， 并拷贝新文件
                    if(targetFile.exists())
                        targetFile.delete();
                    sourceFile.renameTo(targetFile);

                    Integer fileListSize = dir.list().length;
                    if(fileListSize == 0)
                    {
                        log.info("目录为空，需要删除数据文件夹:" + sourceFile.getParent());
                        dir.delete();
                    }
                }
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    public void setResources(Resource[] resources) {
        Assert.notNull(resources, "The resources must not be null");
        this.resources = Arrays.asList(resources).toArray(new Resource[resources.length]);
    }


    public String getBackupFolder() {
        return backupFolder;
    }

    public void setBackupFolder(String backupFolder) {
        this.backupFolder = backupFolder;
    }

    public String getSqlProcess() {
        return sqlProcess;
    }

    public void setSqlProcess(String sqlProcess) {
        this.sqlProcess = sqlProcess;
    }


    public void setDataSource(DataSource dataSource) {
        if (namedParameterJdbcTemplate == null) {
            this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
        }
    }
}
